<?php

/**
 * alltosun.com 订单控制器 index.php
 * ============================================================================
 * 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 吴松键 (wusj@alltosun.com) $
 * $Date: 2014-8-8 下午6:47:43 $
 * $Id$
 */
class Action
{
    private $per_page = 100;

    private function dealer_order_list(array $params = array()) {

        $page_no = $status = $progress = $task_user_id = $search_filter = $is_excel = $status = $exchange_type = $is_payoff = $extra = null;

        extract(URLTracker::init(parse_param(array(
            'search_filter' => array(),
            'page_no' => 1,
            'status' => 1,
            'progress' => '-1',
            'task_user_id' => '-1',
            'is_excel' => 0,
            'status' => 1,
            'exchange_type' => '',
            'extra' => -1,
        ), $params)));

        // 拼装搜索条件
        $filter = array();

        if ($extra == 1) {
            $filter['(confirm_money_name != '] = '';
            $filter['OR confirm_payoff_time > '] = '0000-00-00 00:00:00';
            $filter[') AND 1'] = 1;
        }

        if (isset($search_filter['id']) && $search_filter['id']) {
            $filter['id'] = $search_filter['id'];
        }

        if (isset($search_filter['progress']) && $search_filter['progress'] && $search_filter['progress'] != '-1') {
            $filter['progress'] = $search_filter['progress'];
        }

        if (isset($search_filter['order_code']) && $search_filter['order_code']) {
            $decoded_id = order_helper::order_id_decode($search_filter['order_code']);
            if (is_numeric($decoded_id)) {
                $filter['id'] = $decoded_id;
            }
        }

        if (isset($search_filter['realname']) && $search_filter['realname']) {
            $decoded_id = order_helper::order_id_decode($search_filter['order_code']);
            if (is_numeric($decoded_id)) {
                $filter['id'] = $decoded_id;
            }
        }

        // 获取当前登录人的角色
        $role_id = user_helper::get_admin_role_id();
        if (!user_helper::is_all_can_show($role_id)) {
            $dealer_ids = user_helper::get_dealer_ids_by_areas();
            if ($dealer_ids && is_array($dealer_ids)) {
                $filter['user_id'] = $dealer_ids;
            }
        }

        if (isset($search_filter['user_name']) && $search_filter['user_name']) {
            $user_info = user_helper::get_user_info_by_username($search_filter['user_name']);
            $filter['user_id'] = $user_info['id'];
        }

        if (isset($search_filter['realname']) && $search_filter['realname']) {
            $user_ids = _model('user')->getFields('id', array(
                'realname LIKE ' => '%' . $search_filter['realname'] . '%'
            ));
            if (count($user_ids)) {
                $filter['user_id'] = $user_ids;
            }
        }

        // 下单时间
        if (isset($search_filter['start_date_add']) && $search_filter['start_date_add']) {
            $filter['add_time >='] = $search_filter['start_date_add'] . ' 00:00:00';
        }
        if (isset($search_filter['end_date_add']) && $search_filter['end_date_add']) {
            $filter['add_time <='] = $search_filter['end_date_add'] . ' 23:59:59';
        }

        // 到货时间
        if (isset($search_filter['start_date_receiver']) && $search_filter['start_date_receiver']) {
            $filter['receiver_time >='] = $search_filter['start_date_receiver'] . ' 00:00:00';
        }
        if (isset($search_filter['end_date_receiver']) && $search_filter['end_date_receiver']) {
            $filter['receiver_time <='] = $search_filter['end_date_receiver'] . ' 23:59:59';
        }

        // 支付时间
        if (isset($search_filter['start_date_pay']) && $search_filter['start_date_pay']) {
            $filter['pay_time >='] = $search_filter['start_date_pay'] . ' 00:00:00';
        }
        if (isset($search_filter['end_date_pay']) && $search_filter['end_date_pay']) {
            $filter['pay_time <='] = $search_filter['end_date_pay'] . ' 23:59:59';
        }

        // 总部订单
        $filter['type'] = 1;

        // 状态
        if ($status == 0) {
            $progress = '-1';
            URLTracker::set('progress', '-1', true);
        }

        $filter['status'] = $status;

        if (isset($progress) && $progress != '-1') {
            if ($progress == order_config::DEALER_CANCEL) {
                $filter['progress'] = order_config::DEALER_CANCEL;
            } elseif ($progress == 24) {
                $filter['progress'] = order_config::DEALER_WAIT_SEND_OLD;
                $filter['pay_time <= '] = date("Y-m-d H:i:s", time() - 86400);
                $filter['pay_time >= '] = date("Y-m-d H:i:s", time() - 172400);
            } elseif ($progress == 48) {
                $filter['progress'] = order_config::DEALER_WAIT_SEND_OLD;
                $filter['pay_time <= '] = date("Y-m-d H:i:s", time() - 172400);
            } else {
                $filter['progress'] = intval($progress);
            }

            // 转换
            $filter['progress'] = order_config::dealer_progress_o2n_filter($filter['progress']);
        }

        if (isset($exchange_type) && $exchange_type != '') {
            switch ($exchange_type) {
                case 'bbcoin':
                    // 抱抱币兑换
                    $filter['pay_bbcoin >'] = 0;
                case 'all':
                    // 包含兑换
                    $filter['exchange_num >'] = 0;
                    break;
            }
        }

        // 代理
        if ($task_user_id == 1) {
            $filter['task_user_id > '] = 0;
        } else {
            if ($task_user_id == 0) {
                $filter['task_user_id'] = 0;
            }
        }

        // 获取订单
        $order_list = array();

        $order_count = _model('order')->getTotal(enable_filter($filter));

        if ($order_count) {

            // 所有合伙人信息
            $dealer_list = array_to_filelds_assoc('id', user_helper::get_all_dealers_info());

            $pager = new Pager($this->per_page);
            if ($pager->generate($order_count)) {
                Response::assign('pager', $pager);
            }
            $order_by = ' ORDER BY `id` DESC ';

            if (!$is_excel) {
                $order_by .= $pager->getLimit($page_no);
            }

            $order_list = _model('order')->getList(enable_filter($filter), $order_by);

            $order_list = order_helper::decorator_order_model($order_list);

            foreach ($order_list as $k => $v) {

                // 获取订单分支表信息
                $order_branch_info = _uri('order_branch', array('order_id' => $v['id']));
                if (!empty($order_branch_info)) {
                    $v['receiver_type'] = $order_branch_info['receiver_type'];
                    if (1 == $order_branch_info['receiver_type']) {
                        $v['receiver_extra'] = '合伙人确认到货';
                    } elseif (3 == $order_branch_info['receiver_type']) {
                        $v['receiver_extra'] = '超过七天系统自动确认到货';
                    } elseif (2 == $order_branch_info['receiver_type']) {
                        $v['receiver_extra'] = $order_branch_info['receiver_extra'];
                    } else {
                        $v['receiver_extra'] = '';
                    }
                } else {
                    $v['receiver_type'] = 0;
                    $v['receiver_extra'] = '此单出现致命问题!请联系管理员';
                }

                // 扣完了余额还要付多少
                $v['need_to_pay'] = $v['price'] - $v['pay_user_money'];

                // 合伙人余额
                $v['user_money'] = isset($dealer_list[$v['user_id']]) ? $dealer_list[$v['user_id']]['user_money'] : 0;

                // 够不够扣的
                // 用格式比较
                $v['enough_to_pay'] = num_keep_two_not_round($v['need_to_pay']) >
                                      num_keep_two_not_round($v['user_money']) ? false : true;

                $v['operation'] = order_helper::get_dealer_order_operation($v['id']);

                // 转换状态
                $v['progress'] = order_config::dealer_progress_o2n($v['progress']);

                $order_list[$k] = $v;
            }

            if ($is_excel) {
                $this->export_excel($order_list);
            }
        }

        Response::assign('role_id', $role_id);
        Response::assign('order_list', $order_list);
        Response::assign('order_count', $order_count);
    }

    /**
     * 合伙人订单列表
     */
    public function index() {
        $this->dealer_order_list();
        Response::display('admin/dealer_order_list.html');
    }

    /**
     * 合伙人订单列表::待扣款
     * 综合业务部
     */
    public function dealer_order_confirm() {
        $this->dealer_order_list(array(
            'progress' => order_config::DEALER_WAIT_PAY,
        ));
        $dealer_progress = order_config::$dealer_progress;
        foreach ($dealer_progress as $k => $v) {
            if ($k != order_config::DEALER_WAIT_PAY && $k != order_config::DEALER_WAIT_CONFIRM) {
                unset($dealer_progress[$k]);
            }
        }
        Response::assign('dealer_progress', $dealer_progress);
        Response::display('admin/dealer_order_confirm_list.html');
    }

    /**
     * 合伙人订单列表::待发货
     * 仓库
     */
    public function dealer_order_factory() {
        $this->dealer_order_list(array(
            'progress' => order_config::DEALER_WAIT_PRINT,
        ));
        $dealer_progress = order_config::$dealer_progress;
        foreach ($dealer_progress as $k => $v) {
            if ($k < order_config::DEALER_WAIT_PRINT) {
                unset($dealer_progress[$k]);
            }
        }
        Response::assign('dealer_progress', $dealer_progress);
        Response::display('admin/dealer_order_factory_list.html');
    }


    /**
     * 合伙人订单列表::确认到货
     * 综合助理
     */
    public function dealer_order_done() {
        $this->dealer_order_list(array(
            'progress' => order_config::DEALER_SENDING,
        ));
        $dealer_progress = order_config::$dealer_progress;
        foreach ($dealer_progress as $k => $v) {
            if ($k != order_config::DEALER_SENDING || $k != order_config::DEALER_DONE) {
                unset($dealer_progress[$k]);
            }
        }
        Response::assign('dealer_progress', $dealer_progress);
        Response::display('admin/dealer_order_done_list.html');
    }

    /**
     * 订单明细
     *
     * @return string
     * @throws AnException
     */
    public function order_detail() {
        $id = an_request('id', 0);

        if (!$id) {
            return '访问链接有误，请确认重试';
        }

        $order_info = order_helper::get_order_info($id);
        if (!$order_info) {
            return '访问的订单不存在';
        }

        $order_info = order_helper::decorator_order_model(array($order_info))[0];

        // 杯型信息
        $cup_list_info = cup_helper::get_order_cup_data($id);

        // 获取订单分支表信息
        $order_branch_info = _uri('order_branch', array('order_id' => $order_info['id']));
        if (!empty($order_branch_info)) {
            $order_info['receiver_type'] = $order_branch_info['receiver_type'];
            if (1 == $order_branch_info['receiver_type']) {
                $order_info['receiver_extra'] = '合伙人确认到货';
            } elseif (3 == $order_branch_info['receiver_type']) {
                $order_info['receiver_extra'] = '超过七天系统自动确认到货';
            } elseif (2 == $order_branch_info['receiver_type']) {
                $order_info['receiver_extra'] = $order_branch_info['receiver_extra'];
            } else {
                $order_info['receiver_extra'] = '';
            }
        } else {
            $order_info['receiver_type'] = 0;
            $order_info['receiver_extra'] = '此单出现致命问题!请联系管理员';
        }

        // 扣完了余额还要付多少
        $order_info['need_to_pay'] = $order_info['price'] - $order_info['pay_user_money'];

        // 合伙人余额
        $order_info['user_money'] = $order_info['dealer_info']['user_money'];

        // 够不够扣的
        // 用格式比较
        $order_info['enough_to_pay'] = num_keep_two_not_round($order_info['need_to_pay']) >
                                       num_keep_two_not_round($order_info['user_money']) ? false : true;

        $order_info['operation'] = order_helper::get_dealer_order_operation($order_info['id']);

        // 转换状态
        $order_info['progress'] = order_config::dealer_progress_o2n($order_info['progress']);

        Response::assign('status', $order_info['status']);
        Response::assign('order_id', $id);
        Response::assign('cup_list_info', $cup_list_info);
        Response::assign('order_info', $order_info);
        Response::display('admin/order_detail.html');
    }


    public function print_detail() {
        $id = Request::getParam('id', 0);
        // $status = Request::getParam('status', 1);
        $print_type = Request::getParam('print_type', 1);

        if (!$id) {
            return '访问链接有误，请确认重试';
        }

        $order_info = order_helper::get_order_info($id);
        if (!$order_info) {
            return '访问的订单不存在';
        }

        // 兼容老的
        $order_info['progress'] = order_config::dealer_progress_o2n($order_info['progress']);

        if ($print_type == 2) { // 出库联
            if ($order_info['progress'] < order_config::DEALER_WAIT_PRINT) {
                return array('无法打印, 请先确认订单', 'Failed', AnUrl('order/admin/order_detail.html?id=' . $id));
            } elseif ($order_info['progress'] == order_config::DEALER_WAIT_PRINT) {

                $ret = _model('order')->update(array('id' => $order_info['id']), array(
                    // TODO dealer order 当前没有备货状态, 打印完了直接待发货, 之后为 order_config::DEALER_WAIT_PREPARE
                    'progress' => order_config::DEALER_WAIT_SEND,
                ));

                if ($ret) {
                    // 创建记录
                    order_helper::record_dealer_order_operation($order_info['id'], order_config::DEALER_WAIT_SEND, order_config::DEALER_ACTION_PRINT);
                }
            } else {
                // 重复打印
                order_helper::record_dealer_order_operation($order_info['id'], $order_info['progress'], order_config::DEALER_ACTION_REPRINT);
            }
        }

        $order_info = order_helper::decorator_order_model(array($order_info))[0];
        $order_count = $order_info['goods_num'] + $order_info['exchange_num'];

        // 杯型信息
        Response::assign('cup_list_info', cup_helper::get_order_cup_data($id));
        Response::assign('order_info', $order_info);
        Response::assign('order_count', $order_count);
        Response::assign('print_type', $print_type);

        if ($print_type == 2) { //仓库联
            Response::display('admin/print_storehouse.html');
        } elseif ($print_type == 3) {//财务联
            Response::display('admin/print_detail.html');
        } else { //发货联
            Response::display('admin/print_delivery.html');
        }
    }

    /**
     * TODO 即将废弃
     * 发货
     * @return array
     */
    public function shipping() {

        // 助理,超级管理员允许发货
        $allow_role = array(user_config::ADMIN, user_config::ASSISTANT, user_config::MULTIPLE_DIVISION);
        if (!user_helper::is_allow_action($allow_role)) {
            return '没有此操作权限';
        }

        $id = an_request('id', 0);
        $express_no = an_request('express_no');
        $express_name = an_request('express_name');
        $express_note = an_request('express_note');

        if (!$id) {
            return '请选择要发货的订单';
        }

        //         if (!$express_name) {
        //             return '请填写物流公司';
        //         }

        //         if (!$express_no) {
        //             return '请填写物流编号';
        //         }

        $order_info = _uri('order', array('id' => (int)$id, 'status' => 1));
        if (!$order_info) {
            return '该订单不存在或失效';
        }
        if ($order_info['progress'] != 3) {
            return '该订单不在未发货状态，不能发货';
        }

        $info = array(
            'progress' => 5,
            'deliver_time' => date('Y-m-d H:i:s', time()),
            'express_no' => $express_no,
            'express_name' => $express_name,
            'express_note' => $express_note
        );
        _model('order')->update($id, $info);

        // 统计流水
        order_helper::save_order_status_log($id, 'transport', $info);

        // 发送短信给合伙人
        _widget('dealers.message')->transport_order_message($order_info, $express_name, $express_no);
        return 'ok';
    }

    /**
     * TODO 即将废弃
     * 收款
     * @return array
     */
    public function confirm_pay() {

        // 允许确认收款的只有财务和超级管理员
        $allow_role = array(user_config::FINANCIAL_MANAGEMENT, user_config::ADMIN);
        if (!user_helper::is_allow_action($allow_role)) {
            return '没有此操作权限';
        }

        $id = an_request('id', 0);
        $confirm_money_note = an_request('confirm_money_note');
        if (!$id) {
            return '请选择要收款的订单！';
        }

        $confirm_money_name = an_request('confirm_money_name');
        if (!$confirm_money_name) {
            return '请填写收款人的姓名！';
        }

        $confirm_money_time = an_request('confirm_money_time');
        if (!$confirm_money_time) {
            return '请填写要收款的时间！';
        }

        $order_info = _uri('order', array('id' => (int)$id, 'status' => 1));
        if (!$order_info) {
            return '该订单不存在或失效';
        }
        if ($order_info['progress'] != 1) {
            return '该订单不在未收款状态，不能收款';
        }

        $info = array(
            'confirm_money_note' => $confirm_money_note,
            'confirm_money_name' => $confirm_money_name,
            'confirm_money_time' => $confirm_money_time,
            'progress' => 3,
            'pay_time' => date('Y-m-d H:i:s', time())
        );
        _model('order')->update($id, $info);

        $data = array(
            'confirm_money_note' => $confirm_money_note,
            'confirm_money_name' => $confirm_money_name,
            'confirm_money_time' => $confirm_money_time,
        );

        // 记录流水
        order_helper::save_order_status_log($id, 'payment', $data);

        // 发送短信
        _widget('order.message')->confirm_pay_message($id);

        return 'ok';
    }

    /**
     * TODO 即将废弃
     *
     * 确认到货
     */
    public function finish_dealer_order() {
        $order_id = Request::getParam('id', 0);
        $receiver_extra = Request::getParam('receiver_extra', '');
        if (!$order_id) {
            return '订单ID未知';
        }

        if (!$receiver_extra) {
            return '确认到货备注不能为空';
        }

        $order_no = order_helper::order_id_encode($order_id, 1);

        $result = _widget('order')->confirm_order_progress($order_no, 2, $receiver_extra);

        if ($result['flag']) {
            return 'ok';
        } else {
            return $result["info"];
        }
    }

    /**
     * 取消订单
     * 门店还在用, 不可删除
     *
     * @return string
     */
    public function cancel_order() {
        // 只有财务,助理,超级管理员允许
        $allow_role = array(user_config::ADMIN, user_config::ASSISTANT);
        if (!user_helper::is_allow_action($allow_role)) {
            return '没有此操作权限';
        }

        $id = an_request('id', 0);
        $reason = an_request('order_reason');

        if (!$id) {
            return '请选择要取消的订单';
        }

        if (!$reason) {
            return '请选择要取消订单的理由';
        }

        $info = array(
            'progress' => 15,
            'reason' => $reason,
            'cancel_order_time' => date('Y-m-d H:i:s'),
            'cancel_order_user_id' => user_helper::get_admin_id()
        );
        // 记录流水
        order_helper::save_order_status_log($id, 'cancel', array('desc' => $reason));

        _model('order')->update($id, $info);

        // TODO pay 退回已付款项
        order_helper::cancel_order_send_back($id, $reason);

        return 'ok';
    }

    /**
     * 删除
     * @return array
     */
    public function delete() {
        $id = Request::getParam('id');

        if (!$id) {
            return '请选择要删除的内容';
        }

        $ids = explode(',', trim($id, ','));
        foreach ($ids as $k => $v) {
            if (!$v) {
                continue;
            }

            $order_info = _uri('order', (int)$v);
            if (!$order_info) {
                continue;
            }

            // TODO 删除之前必须先取消!
            if ($order_info['progress'] != order_config::DEALER_CANCEL) {
                return '删除失败, 必须先取消订单才可删除, 订单编号: ' . order_helper::order_id_encode($order_info['id']);
            }

            if (1 == $order_info['status']) {
                _model('order')->update($v, array('status' => 0));
            }
        }

        return 'ok';
    }

    /**
     * 更改状态(还原)
     * @return array
     */
    public function change_status() {
        $id = Request::getParam('id', 0);
        $status = Request::getParam('status', 1);

        if (!$id) {
            return '请选择要更改的内容';
        }

        $order_info = _uri('order', $id);
        if ($status == $order_info['status']) {
            return '已经执行过此操作，不用重复提交';
        }

        if (0 == $order_info['status']) {
            _model('order')->update($id, array('status' => 1));
        }

        return 'ok';
    }

    /**
     * ajax查看快递号
     * @return array
     */
    public function check_express() {
        $order_id = Request::getParam('order_id', 0);
        if (!$order_id) {
            return '请选择要更改的内容';
        }

        $order_info = _uri('order', $order_id);
        foreach ($order_info as $k => $v) {
            if (!is_numeric($v)) {
                $order_info[$k] = trim(AnFilter::filter_string($v));
            }
        }

        return array('info' => 'ok', 'order_info' => $order_info, 'express_no' => $order_info['express_no']);
    }

    /**
     * ajax发货
     * @return array
     */
    public function send_goods() {
        $order_id = Request::getParam('order_id', 0);
        $express_no = Request::getParam('express_no', '');

        if (!$order_id) {
            return '请选择要更改的内容';
        }
        if (!$express_no) {
            return '请输入正确的快递单号';
        }
        $express_time = date('Y-m-d H:i:s', time());
        $send = _model('order')->update($order_id, array(
            'order_status' => 3,
            'express_no' => $express_no,
            'deliver_time' => $express_time
        ));
        $pay_method = _uri('order', $order_id, 'pay_method');

        if ($send) {
            return array(
                'info' => 'ok',
                'order_code' => order_helper::order_id_encode($order_id),
                'express_no' => $express_no,
                'pay_method' => $pay_method
            );
        } else {
            return '未做任何改变！';
        }
    }

    /**
     * 显示退款商品列表
     */
    public function check_refund() {
        $id = Request::getParam('order_id', 0);
        $status = Request::getParam('status', 0);

        if (!$id) {
            return '请选择需要退款的订单';
        }

        $order_info = _uri('order', $id);
        $order_relation_list = order_helper::get_order_relation_by_order_id($id, 'goods_price');
        $coupon_price = coupon_helper::get_coupon_price($order_info['coupon_code']);

        if ($order_info['order_status'] != 4) {
            return '当前订单不能退款';
        }

        // 获取退款列表
        $refund_list = array();
        foreach ($order_relation_list as $k => $v) {
            $info = $v;
            $info['refund_price'] = $v['goods_price'] * $v['goods_num'];
            if (order_helper::check_is_refund($v['id'])) {
                if ($status && order_helper::check_refund_status($v['id']) == $status) {
                    $refund_list[] = $info;
                } else {
                    if (!$status) {
                        $refund_list[] = $info;
                    }
                }
            }
        }
        $goods_total = 0;
        foreach ($refund_list as $k => $v) {
            if (order_helper::check_refund_status($v['id']) == 1) {
                $refund_list[$k]['refund_status'] = '买家申请退款';
            } else {
                if (order_helper::check_refund_status($v['id']) == 2) {
                    $refund_list[$k]['refund_status'] = '退款处理中';
                } else {
                    if (order_helper::check_refund_status($v['id']) == 3) {
                        $refund_list[$k]['refund_status'] = '成功退款';
                    } else {
                        if (order_helper::check_refund_status($v['id']) == 4) {
                            $refund_list[$k]['refund_status'] = '退款失败';
                        }
                    }
                }
            }
            $refund_list[$k]['goods_title'] = cut_str($v['goods_title'], 12, '...');
            $goods_total += $v['goods_price'] * $v['goods_num'];
        }

        if (!$goods_total) {
            return '当前退款不存在';
        }

        return array(
            'info' => 'ok',
            'coupon_price' => $coupon_price,
            'refund_list' => $refund_list,
            'total_price' => $goods_total
        );
    }

    /**
     * 同意退款
     */
    public function refund_agree() {
        $ids = Request::getParam('ids', '');
        $ids = explode(',', $ids);

        if (empty($ids)) {
            return '请选择同意退款的商品';
        }

        foreach ($ids as $k => $v) {
            $filter = array('order_relation_id' => $v, 'status' => 1);
            $refund_info = _uri('refund', $filter);
            if (!empty($refund_info)) {
                _model('refund')->update($filter, array('status' => 3));
            }
        }

        return 'ok';
    }

    /**
     * 不同意退款
     */
    public function refund_cancel() {
        $ids = Request::getParam('ids', '');
        $ids = explode(',', $ids);

        if (empty($ids)) {
            return '请选择同意退款的商品';
        }

        foreach ($ids as $k => $v) {
            $filter = array('order_relation_id' => $v, 'status' => 1);
            $refund_info = _uri('refund', $filter);
            if (!empty($refund_info)) {
                _model('refund')->update($filter, array('status' => 4));
            }
        }

        return 'ok';
    }

    public function get_goods() {
        $pid = Request::Post('pid', 0);
        $method = Request::Post('method', '');
        $number = Request::Post('number', '');

        if ($pid < 0) {
            return array('info' => 'ok', 'data' => '');
        }

        if ($method == 'sku_info') {
            $sku_info = _uri('sku', $pid);
            $sku_info['sku_relation'] = _model('sku_relation')->getList(array('sku_id' => $pid));
            return array('info' => 'ok', 'data' => $sku_info);
        }

        $list = array();
        $tmp = '';
        $end = '';
        $class = '';
        $tmp_number = '';
        $list = _model('category')->getList(array('parent_id' => $pid, 'res_name' => 'goods', 'status' => 1));

        if ($list) {
            $tmp = '分类';
            $htmlid = 'category' . $pid;
            $class = 'js_category';
        } else {
            $tmp = '商品';
            $end = 'data-info="end"';
            $htmlid = 'goods';
            $class = 'js_goods';
            $goods_ids = _model('goods')->getFields('id', array('category_id' => $pid, 'status' => 1));
            if (!$goods_ids) {
                return array('info' => 'ok', 'data' => '<div style="padding:10px;">该分类下没有商品</div>');
            }
            $list = _model('sku')->getList(array('goods_id' => $goods_ids, 'status' => 1));
            foreach ($list as $k => $v) {
                $tmp_title = _uri('goods', array('id' => $v['goods_id']), 'title');
                $property_value = array();
                $property_value = _model('sku_relation')->getFields('tmp_value', array('sku_id' => $v['id']));
                sort($property_value);
                $property = join(' ', $property_value);
                $list[$k]['title'] = $tmp_title . ' ' . $property;
            }
            if ($number == 'number') {
                $tmp_number = '<div style="padding:10px;">数　　　量: <input class="goods_number" value="1"></div>';
            }
        }

        $info = '<div style="padding:10px;">请选择' .
                $tmp .
                ': <select id="' .
                $htmlid .
                '" class="' .
                $class .
                '" ' .
                $end .
                '><option value="-1">请选择' .
                $tmp .
                '</option>';

        foreach ($list as $v) {
            $info .= '<option value="' . $v['id'] . '">' . $v['title'] . '</option>';
        }

        $info .= '</select></div>' . $tmp_number;

        return array('info' => 'ok', 'data' => $info);

        //         Response::assign('list', $list);
        //         Response::assign('htmlid', $htmlid);
        //         Response::assign('method', $method);
        //         Response::display('admin/get_goods.html');
    }

    public function add_order_goods() {
        $id = Request::Post('id', 0);
        $order_id = Request::Post('order_id', 0);
        $number = Request::Post('number', 0);

        if (!$id) {
            return '请选择要添加的商品';
        }

        if (!$order_id) {
            return '请选择要添加商品的订单';
        }

        if (!$number) {
            return '请填写要添加商品的数量';
        }

        $sku_info = _uri('sku', $id);
        $order_info = _uri('order', $order_id);

        if (!$sku_info) {
            return '要添加的商品不存在或失效';
        }
        if (!$order_info) {
            return '要添加商品的订单不存在或失效';
        }

        if ($sku_info['stock'] < $number) {
            return '库存不够';
        }

        $order_relation_list = _model('order_relation')->getList(array('order_id' => $order_id, 'status' => 1));

        foreach ($order_relation_list as $k => $v) {
            if ($sku_info['id'] == $v['sku_id'] && $sku_info['price'] == $v['goods_price']) {
                $relation_number = $v['goods_num'] + $number;
                $order_price = $order_info['price'] + ($sku_info['price'] * $number);
                _model('order_relation')->update($v['id'], array('goods_num' => $relation_number));
                _model('order')->update($v['order_id'], array('price' => $order_price));
                return 'ok';
            }
        }
        $info = array(
            'order_id' => $order_id,
            'user_id' => $order_info['user_id'],
            'goods_id' => $sku_info['goods_id'],
            'sku_id' => $sku_info['id'],
            'sku_snapshot_id' => 0,
            'goods_num' => $number,
            'goods_price' => $sku_info['price'],
            'status' => 1
        );

        $order_price = $order_info['price'] + ($number * $sku_info['price']);

        $new_id = _model('order_relation')->create($info);
        $sku_snapshot_id = goods_helper::create_sku_snapshot($sku_info['id'], $new_id);

        if (!$sku_snapshot_id) {
            _model('order_relation')->delete($new_id);
            return '添加失败';
        }
        _model('order_relation')->update($new_id, array('sku_snapshot_id' => $sku_snapshot_id));
        _model('order')->update($order_id, array('price' => $order_price));

        return 'ok';
    }

    /**
     * 更新snCode编码
     */
    public function update_sn_code() {
        $sn_code = Request::getParam('sn_code', '');
        $invoice_no = trim(Request::getParam('invoice_no', ''));
        $invoice_code = trim(Request::getParam('invoice_code', ''));
        if (!$sn_code) {
            return '请填写sn编码';
        }
        if (!$invoice_no) {
            return '请填写发票号';
        }

        $sn_arr = explode('#', $sn_code);
        $order_id = '';
        foreach ($sn_arr as $k => $v) {
            $relation_arr = explode(':', $v);
            _model('order_relation')->update($relation_arr[0], array('sn_code' => $relation_arr[1]));
            if (!$order_id) {
                $order_id = _uri('order_relation', $relation_arr[0], 'order_id');
            }
        }
        _model('order')->update($order_id, array('invoice_no' => $invoice_no, 'invoice_code' => $invoice_code));

        return false;
    }

    /**
     * 用户订单表
     */
    public function export_excel($list = array()) {
        //        var_dump($list);
        //        exit();
        //初始化excel对象
        $objPHPExcel = new PHPExcel();
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        //设置当前的sheet索引，用于后续的内容操纵
        $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet = $objPHPExcel->getActiveSheet();
        // 哪几列
        $col_arr = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R');
        // 第一排的标题
        $col_title_arr = array(
            '序号',
            '订单编号',
            '商品名称',
            '单价',
            '实际支付',
            '商品数量',
            '总数量',
            '总价',
            '总抱抱币',
            '姓名',
            '手机号',
            '杯型信息(杯)',
            '订单类型',
            '订单状态',
            '支付方式',
            '仓库地址',
            '合伙人余额',
            '合伙人剩余抱抱币',
        );
        $col_content_arr = array(
            'number',
            'order_id',
            'goods_title',
            'goods_price',
            'real_price',
            'goods_num',
            'sum',
            'price',
            'bbcoin_sum',
            'username',
            'mobile',
            'cup_info',
            'order_type',
            'progress',
            'pay_type',
            'dealer_address',
            'user_money',
            'user_bbcoin',
        );
        // 设置文档属性
        foreach ($col_arr as $k => $v) {
            //设置4个列的宽度
            if (in_array($v, array('A'))) {
                $objActSheet->getColumnDimension($v)->setWidth(8);
            } else {
                $objActSheet->getColumnDimension($v)->setWidth(20);
            }
            //设置单位格内容A1,B1,C1,D1
            $objActSheet->setCellValue($v . "1", $col_title_arr[$k]);
            //格式化数字为字符串，避免导致数字默认右对齐单元格
            //            $objActSheet->getStyle($v)->getNumberFormat()->setFormatCode("@");
            //设置自动换行
            $objActSheet->getStyle($v)->getAlignment()->setWrapText(true);
        }

        // 填充单元格
        $key = 2;
        $mergeArr = array('A', 'B', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R');
        foreach ($list as $k => $v) {
            $mergeCells = $v['order_relation_count'] + $v['order_exchange_relation_count'];
            if ($mergeCells > 1) {
                $objActSheet->mergeCells('A' . $key . ':A' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('B' . $key . ':B' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('G' . $key . ':G' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('H' . $key . ':H' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('I' . $key . ':I' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('J' . $key . ':J' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('K' . $key . ':K' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('L' . $key . ':L' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('M' . $key . ':M' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('N' . $key . ':N' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('O' . $key . ':O' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('P' . $key . ':P' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('Q' . $key . ':Q' . ($key + $mergeCells - 1));
                $objActSheet->mergeCells('R' . $key . ':R' . ($key + $mergeCells - 1));
            }

            $order_type_list = order_config::$order_type;
            $cup_name_list = cup_config::$cup_type;
            $pay_type_list = order_config::$pay_type;
            $order_progress = order_config::$dealer_progress;
            // 先将合并的信息填入excl
            $user_info = user_helper::get_user_info($v['user_id']);

            foreach ($col_arr as $k2 => $v2) {
                $place = $v2 . $key;
                $col_content = $col_content_arr[$k2];
                if (!in_array($v2, $mergeArr)) {
                    continue;
                }

                $value = '';
                if ($col_content == 'order_id') {
                    $value = order_helper::order_id_encode($v['id']);
                } elseif ($col_content == 'price') {
                    $value = $v['price'];
                } elseif ($col_content == 'bbcoin_sum') {
                    $value = $v['pay_bbcoin'];
                } elseif ($col_content == 'pay_type') {
                    $value = $pay_type_list[$v['pay_type']];
                } elseif ($col_content == 'sum') {
                    //订单总商品数
                    $value = $v['goods_num'] + $v['exchange_num'];
                } elseif ($col_content == 'username') {
                    // 商家信息
                    //                    $user_info = user_helper::get_user_info($v['user_id']);
                    $value = @$user_info['realname'];
                } elseif ($col_content == 'mobile') {
                    // 商家信息
                    //                    $user_info = user_helper::get_user_info($v['user_id']);
                    $value = @$user_info['mobile'];
                } elseif ($col_content == 'cup_info') {
                    // 杯型信息
                    $cup_list_info = cup_helper::get_order_cup_data($v['id']);
                    if (!$cup_list_info) {
                        $value = '没有散装商品';
                    } else {
                        $value = '';
                        foreach ($cup_list_info as $cup_k => $cup_v) {
                            $value .= $cup_name_list[$cup_v['cup_type']] . '：' . $cup_v['true_cup_num'] . "\r";
                        }
                    }
                } elseif ($col_content == 'order_type') {
                    $value = $order_type_list[$v['type']];
                } elseif ($col_content == 'progress') {
                    $value = $order_progress[$v['progress']];
                } elseif ($col_content == 'number') {
                    $value = $k + 1;
                } elseif ($col_content == 'dealer_address') {
                    $value = $v['dealer_address'];
                } elseif ($col_content == 'user_money') {
                    $value = @$user_info['user_money'];
                } elseif ($col_content == 'user_bbcoin') {
                    //                    $user_info = user_helper::get_user_info($v['user_id']);
                    $value = @$user_info['bbcoin'];
                }

                $objActSheet->setCellValue($place, $value);
            }
            foreach ($v['order_relation'] as $r_k => $order_relation_info) {
                $num = $key + $r_k;
                $goods_info = goods_helper::get_goods_info($order_relation_info['goods_id']);
                $goods_title = $goods_info['title'];
                $goods_price = $order_relation_info['goods_price'];
                $goods_num = $order_relation_info['goods_num'];
                $real_price = $order_relation_info['real_price'];
                $objActSheet->setCellValue('C' . $num, $goods_title);
                $objActSheet->setCellValue('D' . $num, ' ' . $goods_price);
                $objActSheet->setCellValue('E' . $num, $real_price);
                $objActSheet->setCellValue('F' . $num, $goods_num);
            }
            foreach ($v['order_exchange_relation'] as $r_e_k => $order_exchange_relation_info) {
                $num = $key + $v['order_relation_count'] + $r_e_k;
                $goods_info = goods_helper::get_goods_info($order_exchange_relation_info['goods_id']);
                $goods_title = $goods_info['title'];
                $goods_price = $order_exchange_relation_info['goods_price'];
                $goods_num = $order_exchange_relation_info['goods_num'];
                $real_price = $order_exchange_relation_info['real_price'];
                $objActSheet->setCellValue('C' . $num, $goods_title);
                $objActSheet->setCellValue('D' . $num, ' ' . $goods_price);
                $objActSheet->setCellValue('E' . $num, $real_price);
                $objActSheet->setCellValue('F' . $num, $goods_num);
            }


            if ($mergeCells > 1) {
                $key += $mergeCells;
            } else {
                $key++;
            }
        }

        //        exit();

        //设置页面类型
        header("Content-Type: application/vnd.ms-excel");
        //用于下载的文件头
        header("Content-Type: application/force-download");
        header("Content-Type: application/download");
        header("Content-Type: application/octet-stream");

        //$title = trim($catebirthday_gift_recordry_name."表").".xls";
        $title = date('Y-m-d') . "合伙人订单信息.xls";
        // ff正常，ie不正常，下面是从网站找到的解决方案
        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {
            $title = rawurlencode($title);
        }
        header("Content-Disposition: attachment; filename=" . $title);
        header("Content-Transfer-Encoding: binary");
        //最后修改时间
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        //不使用缓存
        header('Cache-Control: ust-revalidate, post-check=0, pre-check=0');
        header('Cache-Control: public');
        header("Expires: 0");
        header("Pragma: public");
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 统计订单数
     */
    public function count_order_num() {
        $admin_id = user_helper::get_admin_id();

        return order_helper::get_assistant_dealer_order_total_num($admin_id);
    }

    /**
     * TODO 即将废弃
     * ajax提交支付凭证
     */
    public function create_payoff() {
        $id = Request::getParam('id', 0);
        $payoff_person = Request::getParam('payoff_person', '');
        $payoff_money = Request::getParam('payoff_money', '');
        $payoff_time = Request::getParam('payoff_time', '0000-00-00');
        $payoff_extra = Request::getParam('payoff_extra', '');

        if (!$id) {
            return '未选择订单!';
        }

        if (!$payoff_person || !$payoff_time) {
            return '支付凭证信息不完整!';
        }

        $reg = '/^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2})?$/';
        if (!preg_match($reg, $payoff_time)) {
            return '支付日期格式不正确!';
        }

        if (!is_numeric($payoff_money) || !$payoff_money) {
            return '付款金额格式不正确';
        }

        $order_info = _uri('order', $id);
        if (!$order_info) {
            return '此订单不存在';
        }

        // 用来判断只能改一次
        //         if ($order_info['payoff_person'] || $order_info['payoff_time']) {
        //             return '不允许重复修改支付凭证';
        //         }

        $info = array(
            'payoff_person' => $payoff_person,
            'payoff_money' => $payoff_money,
            'payoff_time' => $payoff_time,
            'payoff_extra' => $payoff_extra,
            'is_payoff' => 1,
            'confirm_payoff_time' => date('Y-m-d H:i:s')
        );

        _model('order')->update($id, $info);

        return 'ok';
    }

    /**
     * 送货单审批
     *
     * @throws AnException
     */
    public function ajax_delivery_note_verify() {

        $P = array();

        $P['order_id'] = an_request('order_id', 0);
        $P['delivery_status'] = an_request('delivery_status');
        $P['reject_reason'] = an_request('reject_reason');
        $P['action'] = an_request('action');
        $P['changed_bbcoin'] = an_request('changed_bbcoin');
        $P['changed_reason'] = trim(an_request('changed_reason'));

        if (!$P['action']) {
            return_data(1, '无任何操作!');
        }

        if (!$P['order_id']) {
            return_data(1, '订单编号错误');
        }

        $order_detail = _model('order')->getList(array('id' => $P['order_id']));
        if (count($order_detail)) {
            $order_detail = array_shift($order_detail);
        }
        $order_delivery_note = order_helper::get_order_delivery_note_info_by_order_id($P['order_id']);

        if ($P['delivery_status'] != $order_delivery_note['status']) {
            return_data(1, '送货单状态已变更，请刷新页面');
        }

        $set_delivery = array();
        $set_order = array();

        switch ($P['action']) {
            case 'preview':
                // 预审
                if ($order_delivery_note['status'] === '1') {
                    $set_delivery['status'] = 5;
                    _model('order')->update(array('id' => $P['order_id']), array('delivery_note_status' => $set_delivery['status']));
                    $ret = _model('order_delivery_note')->update(array('order_id' => $P['order_id']), $set_delivery);
                    if ($ret) {
                        return_data(0, '操作成功', array('delivery_status' => $set_delivery['status']));
                    }
                }
                break;
            case 'accept':
                // 审核

                // 白条支付
                if ($order_detail['is_ious'] === '1') {
                    //获取店铺名称
                    $store_title = store_helper::get_store_title($order_detail['store_id']);

                    // 已上传, 未回款, 已预审, 返还余额
                    if ($order_delivery_note['status'] === '5') {

                        // 置 => 送货单状态为已审核
                        $set_delivery['status'] = '2';

                        // 下发余额
                        if ($order_delivery_note['is_return_cash'] != 1) {
                            $return_cash = $order_delivery_note['return_cash'];

                            //$extra = '白条支付返还，金额 ' . $return_cash . ';';
                            //修改备注文案 author:xiaolin date:2016-10-31
                            $extra = $store_title . '回款返还，金额 ' . $return_cash . ';';

                            // user_id: 合伙人
                            $res = user_money_helper::change_user_money(array(
                                'user_id' => $order_detail['agency_id'],
                                'user_money' => $return_cash,
                                'order_id' => $order_detail['id'],
                                'store_id' => $order_detail['store_id'],
                                'res_id' => user_money_config::RES_TYPE_IOUS_RETURN,
                                'admin_id' => user_helper::get_user_id(),
                                'extra' => $extra,
                            ));

                            if (!$res) {
                                return_data(1, '余额下发失败，请稍后重试');
                            }

                            $set_delivery['return_cash_time'] = datetime(); // 下发余额时间
                            $set_delivery['is_return_cash'] = 1; // 标识已下发余额
                        }
                    }

                    // 已上传, 已回(影院)/付(普通门店)款, 已审过(影院), 返还抱抱币
                    if ($order_delivery_note['status'] === '2' ||
                        ($order_delivery_note['status'] === '5' && $order_detail['is_pay'] === '1')
                    ) {
                        // 置 => 送货单状态为完成
                        $set_delivery['status'] = '4';

                        // 下发抱抱币
                        if ($order_delivery_note['is_return_bbcoin'] != 1) {
                            $return_bbcoin = $order_delivery_note['return_bbcoin'];
                            //$extra = '白条自动返还，数量 ' . $return_bbcoin . ';';
                            //修改备注文案 author:xiaolin date:2016-10-31
                            $extra = $store_title . '回款返还，数量 ' . $return_bbcoin . ';';

                            if (is_numeric($P['changed_bbcoin'])) {
                                if (trim($P['changed_reason']) == '') {
                                    return_data(1, '抱抱币更改理由不能为空');
                                }
                                $return_bbcoin = $P['changed_bbcoin'];
                                $extra .= ' 变更为: ' . $return_bbcoin . '; 变更备注: ' . $P['changed_reason'];
                            }

                            // user_id: 合伙人
                            $res = bbcoin_helper::change_bbcoin(array(
                                'user_id' => $order_detail['agency_id'],
                                'bbcoin' => $return_bbcoin,
                                'order_id' => $order_detail['id'],
                                'store_id' => $order_detail['store_id'],
                                'res_id' => bbcoin_config::RES_TYPE_IOUS_RETURN,
                                'admin_id' => user_helper::get_user_id(),
                                'extra' => $extra,
                            ));

                            if (!$res) {
                                return_data(1, '抱抱币下发失败，请稍后重试');
                            }
                            $set_delivery['return_bbcoin'] = $return_bbcoin; // 实际下发的抱抱币
                            $set_delivery['return_bbcoin_time'] = datetime(); // 下发的抱抱币时间
                            $set_delivery['is_return_bbcoin'] = 1; // 标识已下发抱抱币
                        }

                    }

                    if ($order_delivery_note['status'] === '5') {
                        // 置 => 送货单状态为已审核
                        // $set_delivery['status'] = '2';
                        // 审核时间
                        $set_delivery['verify_time'] = datetime();
                    }

                    if ($order_delivery_note['status'] === '2') {
                        // 置 => 状态为已支付
                        $set_order['is_pay'] = '1';
                        $set_order['pay_time'] = datetime();
                        $ret = _model('order')->update(array('id' => $P['order_id']), $set_order);
                        if (!$ret) {
                            return_data(1, '操作失败，无法设置支付状态');
                        }
                    }
                } else { // 影院的, 单独审核, 直接过
                    $set_delivery['status'] = '4';
                    $set_delivery['verify_time'] = datetime();
                }

                if (count($set_delivery)) {
                    _model('order')->update(array('id' => $P['order_id']), array('delivery_note_status' => $set_delivery['status']));
                    $ret = _model('order_delivery_note')->update(array('order_id' => $P['order_id']), $set_delivery);
                    if ($ret) {
                        return_data(0, '操作成功', array('delivery_status' => $set_delivery['status']));
                        // TODO 发送短信
                    }
                    return_data(1, '操作失败，请稍后重试');
                }

                break;

            case 'reject':
                $P['reject_reason'] = trim($P['reject_reason']);
                if (!$P['reject_reason']) {
                    return_data(1, '驳回理由不能为空');
                }
                // 驳回
                $set_delivery['reject_reason'] = $P['reject_reason'];
                $set_delivery['status'] = '3';
                $set_delivery['verify_time'] = datetime();

                _model('order')->update(array('id' => $P['order_id']), array('delivery_note_status' => $set_delivery['status']));
                $ret = _model('order_delivery_note')->update(array('order_id' => $P['order_id']), $set_delivery);
                if ($ret) {
                    return_data(0, '驳回送货单成功', array('delivery_status' => $set_delivery['status']));
                    // TODO 发送短信
                }

                return_data(1, '驳回失败，请稍后重试');
                break;
        }

        return_data(1, '无效的操作');

        // 未审核
    }

    /**
     * 获取实时数据
     *
     * @throws AnException
     */
    public function ajax_get_real_time_order_data() {
        $order_id = an_request('order_id', 0);

        if (!$order_id) {
            return_data(1, '未指定订单');
        }
        $order_info = _model('order')->read(array('id' => $order_id));
        $order_info['no'] = order_helper::order_id_encode($order_info['id']);
        $order_info['need_to_pay'] = num_keep_two_round($order_info['price'] - $order_info['pay_user_money']);

        $order_info['user_info'] = _uri('user', $order_info['user_id']);

        $order_info['overage'] = num_keep_two_round($order_info['user_info']['user_money'] -
                                                    $order_info['need_to_pay']);

        return_data(0, 'success', $order_info);

    }

    // 暂时无用
    public function delivery_note_pay_back_verify() {

    }

}

?>